#!usr/bin/env python3
# encoding:utf-8
from uu import decode
from flask import Flask
from flask import render_template
import requests
import uuid
from urllib.parse import urlencode, unquote
from flask import request
from flask import jsonify
import os, sys
os.path.join(os.path.dirname(__file__), '../')
sys.path.append(os.path.join(os.path.dirname(__file__), '../'))
from public import pmysql

app = Flask(__name__, template_folder='templates')
app.config['JSON_AS_ASCII'] = False
app.config['JSONIFY_MIMETYPE'] = "application/json;charset=utf-8"


pm = pmysql.pmy()

@app.route('/')
def index():
    return render_template("index.html")

@app.route('/help')
def help():
    return render_template("help.html")

@app.route('/newspower/task', methods= ["GET"])
def addtask():

    url = request.args.get('url')
    cb = request.args.get('callback')
    udid = request.args.get('udid')
    if(url == None or cb == None):
        resut = {"result":"error", "info":"关键内容为空！"}
        return jsonify(resut)
    if(udid == None):
        udid = "0"
    ret = addtask(url, cb, udid)
    return jsonify(ret)

@app.route('/newspower/query', methods= ["GET"])
def query():

    tid = request.args.get('tid')
    if(tid == None):
        resut = {"result":"error", "info":"tid不能为空"}
        return jsonify(resut)
    ret = querytask(tid)
    return jsonify(ret)

@app.route('/newspower/callback', methods= ["POST"])
def callback():
    dataraw=request.get_json()
    print(dataraw,type(dataraw))
    return jsonify({'status': 'success'})

def addtask(url, cb, udid):
    tid = uuid.uuid1()
    sql = "insert into task (tid, file, callback, ctime, etime, try, status, udid) values ( %s, %s, %s, now(), now(), 0, 'new', %s)" 
    res = pm.update(sql, (tid, url, cb, udid,))
    if res != 1 :
        ret = {"result":"error", "info":"数据库操作错误"}
    else:
        ret = {"tid":tid, "url":url, "callback":cb, "udid":udid, "result":"OK", "info":"生成任务！"}
    return ret

def querytask(tid):

    ret = {"result":"error", "info":"not found"}
    sql = "select status, info from callback where tid = %s"
    res = pm.get_one(sql, (tid,))
    if res != None :
        ret = {"cmd":"callback", "result":res[0], "info":res[1]}
    else:
        sql = "select status, info from task where tid = %s"
        res = pm.get_one(sql, (tid,))
        if res != None :
            ret = {"cmd":"runtask", "result":res[0], "info":res[1]}
    return ret

if __name__ == '__main__':
    app.run(host="0.0.0.0")
